package com.bjsxt.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component("fileUtil")
public class FileUtil
{
	public boolean copy(MultipartFile sourceFile,File targetFile)
	{
		if(!targetFile.getParentFile().exists())
		{
			targetFile.getParentFile().mkdirs();
		}
		BufferedInputStream bis=null;
		BufferedOutputStream bos=null;
		try
		{
			bis=new BufferedInputStream(sourceFile.getInputStream());
			bos=new BufferedOutputStream(new FileOutputStream(targetFile));
			
			int len=0;
			byte[] b=new byte[1024];
			while((len=bis.read(b))!=-1)
			{
				bos.write(b,0,len);
			}
			return true;
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try
			{
				bos.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try
			{
				bis.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return false;
	}
	public boolean copy(File sourceFile,File targetFile)
	{
		if(!targetFile.getParentFile().exists())
		{
			targetFile.getParentFile().mkdirs();
		}
		BufferedInputStream bis = null ; 
		BufferedOutputStream bos = null ; 
		try
		{
			bis=new BufferedInputStream(new FileInputStream(sourceFile));
			bos=new BufferedOutputStream(new FileOutputStream(targetFile));
			byte[] b=new byte[1024];
			int len=0;
			while((len=bis.read(b))!=-1)
			{
				bos.write(b,0,len);
			}
			return true;
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try
			{
				bos.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try
			{
				bis.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return false;
	}
}
